package com.lancoo.tyjx.multichatroom.xmpp;

import android.annotation.SuppressLint;
import android.os.Build;
import android.util.Log;

import com.lancoo.tyjx.multichatroom.activity.MyApplication;
import com.lancoo.tyjx.multichatroom.constants.Constants;
import com.lancoo.tyjx.multichatroom.model.ChatItem;
import com.lancoo.tyjx.multichatroom.model.Room;
import com.lancoo.tyjx.multichatroom.utils.FileUtil;
import com.lancoo.tyjx.multichatroom.utils.ImageUtil;
import com.lancoo.tyjx.multichatroom.utils.JsonUtil;
import com.lancoo.tyjx.multichatroom.utils.Tool;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Registration;
import org.jivesoftware.smack.provider.IQProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.FormField;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.muc.DiscussionHistory;
import org.jivesoftware.smackx.muc.HostedRoom;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.RoomInfo;
import org.jivesoftware.smackx.ping.PingManager;
import org.xmlpull.v1.XmlPullParser;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class XmppTool {

    private static final String TAG = "XmppTool";
    private static XMPPConnection con = null;
    private static XmppTool xmppTool = null;
    public static List<Room> myRooms = new ArrayList<>();
    public static List<Room> leaveRooms = new ArrayList<>();
    private static Chat newchat;
    private static MultiUserChat mulChat;
    private XmppMessageListener messageListener = null;
    private XmppMessageInterceptor xmppMessageInterceptor;
    private Roster roster;
    private List<String> joinedRoom = new ArrayList<>();

    static {
        try {
            Class.forName("org.jivesoftware.smack.ReconnectionManager");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void openConnection() {
        try {
            // url、端口，也可以设置连接的服务器名字，地址，端口，用户。
            ConnectionConfiguration connConfig = new ConnectionConfiguration(
                    Constants.SERVER_HOST, Constants.SERVER_PORT);

            connConfig.setReconnectionAllowed(true);
//			connConfig.setSASLAuthenticationEnabled(false);
            connConfig.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                connConfig.setTruststoreType("AndroidCAStore");
                connConfig.setTruststorePassword(null);
                connConfig.setTruststorePath(null);
            } else {
                connConfig.setTruststoreType("BKS");
                String path = System.getProperty("javax.net.ssl.trustStore");
                if (path == null) {
                    path = System.getProperty("java.home") + File.separator + "etc"
                            + File.separator + "security" + File.separator
                            + "cacerts.bks";
                }
                connConfig.setTruststorePath(path);
            }
//			connConfig.setSendPresence(true);
//			SASLAuthentication.supportSASLMechanism("PLAIN", 0);
//			connConfig.setSendPresence(false);
            con = new XMPPConnection(connConfig);
            con.connect();

            con.addConnectionListener(connectionListener);
            ProviderManager.getInstance().addIQProvider("muc", "MZH",
                    new MUCPacketExtensionProvider());
        } catch (Exception xe) {
            xe.printStackTrace();
            con = null;
        }
    }

    public static ConnectionListener connectionListener = new ConnectionListener() {
        @Override
        public void reconnectionSuccessful() {
            //重连成功
            //重连成功后要重新注册接收消息的Listen,要不然没法接收到消息

            Log.i("connection", "reconnectionSuccessful");
        }


        @Override
        public void reconnectionFailed(Exception arg0) {
            //重连失败
            Log.i("connection", "reconnectionFailed");
        }


        @Override
        public void reconnectingIn(int arg0) {
            //重连中
            Log.i("connection", "reconnectingIn");
        }


        @Override
        public void connectionClosed() {
            Log.i("connection", "connectionClosed");
        }

        @Override
        public void connectionClosedOnError(Exception arg0) {
            Log.i("connection", "connectionClosedOnError");
            //重连失败
        }
    };

    /**
     * 单例模式
     *
     * @return
     */
    public static XmppTool getInstance() {
        if (xmppTool == null) {
            xmppTool = new XmppTool();
        }
        return xmppTool;
    }

    public void setNull() {
        con = null;
    }

    public void loadFriendAndJoinRoom(final String userNmae) {
        new Thread() {
            public void run() {
                // try {
                // sleep(1*1000);
                if (XmppTool.getInstance().getMyRooms() != null) {
                    XmppTool.getInstance().joinMultiUserChat(userNmae,
                            chatRoomName, false);
                }
//					for (Room room : XmppTool.getInstance().getMyRooms()) {
//						XmppTool.getInstance().joinMultiUserChat(userNmae,
//								room.name, false);
//					}
//				}
                // } catch (InterruptedException e) {
                // e.printStackTrace();
                // }
            }

            ;
        }.start();
    }

    public void joinMultiRoom(final String user, final String roomsName) {
        new Thread() {
            @Override
            public void run() {
                joinMultiUserChat(user, roomsName, false);
            }
        }.start();
    }

    /**
     * 注册
     *
     * @param account  注册帐号
     * @param password 注册密码
     * @return 1、注册成功 0、服务器没有返回结果2、这个账号已经存在3、注册失败
     */
    public IQ regist(String account, String password) {
        if (getConnection() == null) {
            return null;
        }
        Registration reg = new Registration();
        reg.setType(IQ.Type.SET);
        reg.setTo(getConnection().getServiceName());
        reg.setUsername(account);
        reg.setPassword(password);
        // reg.addAttribute("android", "geolo_createUser_android");
        PacketFilter filter = new AndFilter(new PacketIDFilter(
                reg.getPacketID()), new PacketTypeFilter(IQ.class));

        PacketCollector collector = getConnection().createPacketCollector(
                filter);
        // 给注册的Packet设置Listener，因为只有等到正真注册成功后，我们才可以交流
        // collector.addPacketListener(packetListener, filter);
        // 向服务器端，发送注册Packet包，注意其中Registration是Packet的子类
        getConnection().sendPacket(reg);

        IQ result = (IQ) collector.nextResult(SmackConfiguration
                .getPacketReplyTimeout());
        // Stop queuing results
        collector.cancel();

        return result;

    }

    //TODO 发送图片
    public void sendImage(String url, String localPath, int chatType) throws Exception {
        if (getConnection() == null) {
            throw new Exception("XmppException");
        }

        File file = new File(localPath);
        String fileName = file.getName();
        String base64 = ImageUtil.getBase64StringFromFile(localPath);
        String base64Path = Constants.SAVE_IMG_PATH + "/" + fileName;
        FileUtil.saveFileByBase64(base64, base64Path);

        String sendMsg = JsonUtil.xmppMsg2Json(XmppMsgType.PICTURE, fileName, base64, url);
        if (chatType == ChatItem.CHAT) {
            newchat.sendMessage(sendMsg);
        } else if (chatType == ChatItem.GROUP_CHAT) {
            mulChat.sendMessage(sendMsg);
            // MyApplication.getInstance().sendBroadcast(new
            // Intent("ChatNewMsg"));
        }
    }

    private static byte[] getFileBytes(File file) throws IOException {
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            int bytes = (int) file.length();
            byte[] buffer = new byte[bytes];
            int readBytes = bis.read(buffer);
            if (readBytes != buffer.length) {
                throw new IOException("Entire file not read");
            }
            return buffer;
        } finally {
            if (bis != null) {
                bis.close();
            }
        }
    }

    /**
     * 登录
     *
     * @param account  登录帐号
     * @param password 登录密码
     * @return
     */
    public boolean login(String account, String password) {
        try {
            if (getConnection() == null)
                return false;
            if (!getConnection().isAuthenticated()
                    && getConnection().isConnected()) {
                getConnection().login(account, password);
                // // 更改在綫狀態
                Presence presence = new Presence(Presence.Type.available);
                // Constants.USER_STATUS = presence.getStatus();
                presence.setMode(Presence.Mode.available);
                getConnection().sendPacket(presence);

                roster = XmppTool.getInstance().getConnection().getRoster();
                // friendListner = new FriendListner();
                // roster.addRosterListener(friendListner);
                // 监听邀请加入聊天室请求
                // MultiUserChat.addInvitationListener(getConnection(), new
                // InvitationListener() {
                //
                // @Override
                // public void invitationReceived(Connection arg0, String arg1,
                // String arg2,
                // String arg3, String arg4, Message arg5) {
                // // TODO Auto-generated method stub
                //
                // }
                // });
                loadFriendAndJoinRoom(account);
                return true;
            }

        } catch (XMPPException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 加入会议室
     *
     * @param user      昵称
     * @param restart   是否需要重启，asmack的错误。新邀请的时候为true
     * @param roomsName 会议室名
     */
    public boolean joinMultiUserChat(String user, String roomsName,
                                     boolean restart) {
        Connection.DEBUG_ENABLED = true;
        if (getConnection() == null) {
            return false;
        }
        // 设置ping(单位s)
        PingManager.getInstanceFor(getConnection()).setPingIntervall(20);
        String multiRoom = roomsName
                + Constants.SERVER_DESC + getConnection().getServiceName();
        System.out
                .println("XmppTool.joinMultiUserChat()=========join multichat=======" + multiRoom);
        // 使用XMPPConnection创建一个MultiUserChat窗口

        if (!isRoomExit(roomsName)) {
            Log.w(TAG, "房间--->" + roomsName + "不存在");
            return createNewRoom(user, roomsName);
        } else {
            Log.w(TAG, "房间--->" + roomsName + "存在");
            return joinRoom(user, roomsName, restart);
        }
    }

    private boolean joinRoom(String user, String roomsName, boolean restart) {
        if (getConnection() == null) {
            return false;
        }
        String multiRoom = roomsName
                + Constants.SERVER_DESC + getConnection().getServiceName();
        mulChat = new MultiUserChat(getConnection(), multiRoom);
        // 聊天室服务将会决定要接受的历史记录数量
        DiscussionHistory history = new DiscussionHistory();
//        history.setMaxChars(0);
//        history.setSince(new Date());
        // 上次离线时间
        history.setSince(new Date("2018/1/1"));
        if (messageListener == null) {
            messageListener = new XmppMessageListener();
            con.addPacketListener(messageListener, new PacketTypeFilter(
                    Message.class));
        }
        if (xmppMessageInterceptor == null) {
            xmppMessageInterceptor = new XmppMessageInterceptor();
            con.addPacketInterceptor(xmppMessageInterceptor, new PacketTypeFilter(
                    Message.class));
        }
        try {
            // 用户加入聊天室
            mulChat.join(user, null, history, SmackConfiguration.getPacketReplyTimeout());
            if (Constants.IS_DEBUG) {
                Log.e("muc", "会议室【" + roomsName + "】加入成功........");
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            if (Constants.IS_DEBUG) {
                Log.e("muc", "会议室【" + roomsName + "】加入失败........" + Constants.SERVER_HOST);
            }
            return false;
        } finally {
            System.out.println("XmppTool.joinMultiUserChat()====" + mulChat.isJoined());
            if (restart) {
//				 reconnect();
            }
        }
    }

    public boolean createNewRoom(String user, String roomsName) {
        if (getConnection() == null) {
            return false;
        }
        try {
            String multiRoom = roomsName
                    + Constants.SERVER_DESC + getConnection().getServiceName();
            mulChat = new MultiUserChat(getConnection(), multiRoom);
            // 创建聊天室
            mulChat.create(user);
            // 获得聊天室的配置表单
            Form form = mulChat.getConfigurationForm();
            // 根据原始表单创建一个要提交的新表单。
            Form submitForm = form.createAnswerForm();
            // 向要提交的表单添加默认答复
            for (Iterator fields = form.getFields(); fields.hasNext(); ) {
                FormField field = (FormField) fields.next();
                if (!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable() != null) {
                    // 设置默认值作为答复
                    submitForm.setDefaultAnswer(field.getVariable());
                }
            }
            // 设置聊天室的新拥有者
            // List<String> owners = new ArrayList<String>();
            // owners.add(getConnection().getUser());// 用户JID
            // submitForm.setAnswer("muc#roomconfig_roomowners", owners);
            // 设置聊天室是持久聊天室，即将要被保存下来
            submitForm.setAnswer("muc#roomconfig_persistentroom", true);
            // 房间仅对成员开放
//            submitForm.setAnswer("muc#roomconfig_membersonly", false);
            // 允许占有者邀请其他人
            submitForm.setAnswer("muc#roomconfig_allowinvites", true);
            submitForm.setAnswer("muc#roomconfig_publicroom", true);
            // if (!password.equals("")) {
            // // 进入是否需要密码
            // submitForm.setAnswer("muc#roomconfig_passwordprotectedroom",false);
            // // 设置进入密码
            // submitForm.setAnswer("muc#roomconfig_roomsecret", password);
            // }
            // 能够发现占有者真实 JID 的角色
            // submitForm.setAnswer("muc#roomconfig_whois", "anyone");
            // 设置描述
//            submitForm.setAnswer("muc#roomconfig_roomdesc", roomsName);
            // 登录房间对话
//            submitForm.setAnswer("muc#roomconfig_enablelogging", true);
            // 仅允许注册的昵称登录
//            submitForm.setAnswer("x-muc#roomconfig_reservednick", false);
            // 允许使用者修改昵称
//            submitForm.setAnswer("x-muc#roomconfig_canchangenick", true);
            // 允许用户注册房间
//            submitForm.setAnswer("x-muc#roomconfig_registration", true);
            // 最大人数
            List<String> list_single = new ArrayList<>();
            list_single.add("10000");
            submitForm.setAnswer("muc#roomconfig_maxusers", list_single);
            // 发送已完成的表单（有默认值）到服务器来配置聊天室
            mulChat.sendConfigurationForm(submitForm);

            if (Constants.IS_DEBUG) {
                Log.e("muc", "会议室【" + roomsName + "】创建成功........");
            }
            return true;
        } catch (Exception e) {
            if (Constants.IS_DEBUG) {
                Log.e("muc", "会议室【" + roomsName + "】创建不成功........");
            }
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 初始化会议室列表
     */
    public List<RoomInfo> getHostRooms() {
        if (getConnection() == null)
            return null;
        Collection<HostedRoom> hostrooms = null;
        List<RoomInfo> roominfos = new ArrayList<>();
        try {
            new ServiceDiscoveryManager(getConnection());
            hostrooms = MultiUserChat.getHostedRooms(getConnection(),
                    getConnection().getServiceName());
            for (HostedRoom entry : hostrooms) {
                for (HostedRoom j : MultiUserChat.getHostedRooms(getConnection(),
                        entry.getJid())) {
                    RoomInfo info2 = MultiUserChat.getRoomInfo(getConnection(),
                            j.getJid());
                    if (j.getJid().indexOf("@") > 0) {

                        roominfos.add(info2);
                    }
                }
            }
            Log.i("room", "服务会议数量:" + roominfos.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return roominfos;
    }

    private boolean isRoomExit(String roomName) {
        List<RoomInfo> list = getHostRooms();
        if (list.isEmpty()) {
            return false;
        } else {
            for (RoomInfo roomInfo : list) {
                if (roomName.equals(roomInfo.getDescription())) {
                    return true;
                }
            }
        }
        return false;
    }

    public void leaveMuc(final String roomName) {
        // 使用XMPPConnection创建一个MultiUserChat窗口
        new Thread() {
            public void run() {
                if (con != null && messageListener != null) {
                    con.removePacketListener(messageListener);
                    con.removePacketInterceptor(xmppMessageInterceptor);
                    messageListener = null;
                    xmppMessageInterceptor = null;
                }
//				mulChat = new MultiUserChat(getConnection(),
//						getFullRoomname(chatRoomName));
                //&& mulChat.isJoined()
                if (mulChat != null) {
                    try {
                        mulChat.leave();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                XmppTool.getInstance().closeConnection();
                if (Constants.IS_DEBUG) {
                    Log.e("muc", "会议室【" + roomName + "】退出成功........");
                }
            }
        }.start();
    }

    public List<Room> getMyRooms() {
        return myRooms;
    }

    /**
     * 通过username获得jid
     *
     * @param username
     * @return
     */
    public String getFullUsername(String username) {
        return username + "@" + getConnection().getServiceName();
    }

    /**
     * 通过roomjid获取房间名
     *
     * @param fullRoomname
     * @return
     */
    public static String getRoomName(String fullRoomname) {
        return fullRoomname.split("@")[0];
    }

    /**
     * 通过jid获得username
     *
     * @param fullUsername
     * @return
     */
    public static String getUsername(String fullUsername) {
        return fullUsername.split("@")[0];
    }

    /**
     * 通过roomName获得roomjid
     *
     * @param roomName
     * @return
     */
    public String getFullRoomname(String roomName) {
        return roomName + Constants.SERVER_DESC + getConnection().getServiceName();
    }

    private String chatRoomName;

    public void setRecevier(String chatName, int chatType) {
        this.chatRoomName = chatName;
        if (getConnection() == null) {
            return;
        }

        if (chatType == ChatItem.CHAT) {
            // 创建回话
            ChatManager cm = XmppTool.getInstance().getConnection()
                    .getChatManager();
            // 发送消息给pc服务器的好友（获取自己的服务器，和好友）
            newchat = cm.createChat(getFullUsername(chatName), null);
        } else if (chatType == ChatItem.GROUP_CHAT) {
//            mulChat = new MultiUserChat(getConnection(),
//                    getFullRoomname(chatName));
            if (null == mulChat) {
                mulChat = new MultiUserChat(getConnection(),
                        getFullRoomname(chatName));
            }
        }
        if (messageListener == null) {
            messageListener = new XmppMessageListener();
            con.addPacketListener(messageListener, new PacketTypeFilter(
                    Message.class));
        }
        if (xmppMessageInterceptor == null) {
            xmppMessageInterceptor = new XmppMessageInterceptor();
            con.addPacketInterceptor(xmppMessageInterceptor, new PacketTypeFilter(
                    Message.class));
        }
//		loadFriendAndJoinRoom(Constants.USER_NAME);
    }

    // 发送文本消息
    @SuppressLint("NewApi")
    public void sendMsg(String msg, int chatType) throws Exception {
        if (getConnection() == null) {
            throw new Exception("XmppException");
        }

        if (msg.isEmpty()) {
            Tool.initToast(MyApplication.getInstance(), "随便写点什么呗");
        } else {
            String sendMsg = JsonUtil.xmppMsg2Json(XmppMsgType.NORMAL, msg);
            if (chatType == ChatItem.CHAT) {
                newchat.sendMessage(sendMsg);
            } else if (chatType == ChatItem.GROUP_CHAT) {
                mulChat.sendMessage(sendMsg);
                // MyApplication.getInstance().sendBroadcast(new
                // Intent("ChatNewMsg"));
            }
        }
    }

    public void sendAskMsg(String user, String msg, String url) throws Exception {
        if (getConnection() == null) {
            throw new Exception("XmppException");
        }

        ChatManager chatmanager = XmppTool.getInstance()
                .getConnection().getChatManager();

        // get user
        // new a session
        Chat chat = chatmanager.createChat(getFullUsername(user), null);

        if (msg.isEmpty()) {
            Tool.initToast(MyApplication.getInstance(), "随便写点什么呗");
        } else {
            String sendMsg = JsonUtil.xmppMsg2Json(XmppMsgType.ASK, msg, url);
            chat.sendMessage(sendMsg);
        }
    }

    /**
     * 发送点赞消息
     *
     * @param msg      like：点赞  unlike：取消点赞
     * @param chatType
     * @throws Exception
     */
    public void sendLikeMsg(String msg, int chatType) throws Exception {
        if (getConnection() == null) {
            throw new Exception("XmppException");
        }
        if (msg.isEmpty()) {
            Tool.initToast(MyApplication.getInstance(), "你是点赞还是取消点赞？");
        } else {
            String sendMsg = JsonUtil.xmppMsg2Json(XmppMsgType.LIKE, msg);
            if (chatType == ChatItem.CHAT) {
                newchat.sendMessage(sendMsg);
            } else if (chatType == ChatItem.GROUP_CHAT) {
                mulChat.sendMessage(sendMsg);
                // MyApplication.getInstance().sendBroadcast(new
                // Intent("ChatNewMsg"));
            }
        }
    }

    /**
     * 发送消息，附带参数
     *
     * @param fileName 文件名
     * @param parms    imgData
     * @param datas    base64编码后的参数
     * @param chatType 聊天类型
     * @throws Exception
     */
    public void sendMsgWithParms(String fileName, String[] parms, Object[] datas,
                                 int chatType, XmppMsgType msgType) throws Exception {
        if (getConnection() == null) {
            throw new Exception("XmppException");
        }

        Message message = new Message();
        for (int i = 0; i < datas.length; i++) {
            message.setProperty(parms[i], datas[i]);
        }
        message.setBody(fileName);
        String sendMsg;
        if (msgType == XmppMsgType.AUDIO) {
            sendMsg = JsonUtil.xmppMsg2Json(msgType, fileName, datas[0], datas[1]);
        } else {
            sendMsg = JsonUtil.xmppMsg2Json(msgType, fileName, datas[0]);
        }

        if (chatType == ChatItem.CHAT) {
            newchat.sendMessage(sendMsg);
        } else if (chatType == ChatItem.GROUP_CHAT) {
            mulChat.sendMessage(sendMsg);
//			mulChat.sendMessage(msg + ":::" + datas[0]);
            // MyApplication.getInstance().sendBroadcast(new
            // Intent("ChatNewMsg"));
        }
    }

    public XMPPConnection getConnection() {
        if (con == null) {
            openConnection();
        }
        return con;
    }

    public boolean isconnected() {
        if (con != null) {
            return con.isConnected();
        }
        return false;
    }

    /**
     * 通过roomjid获取发送者
     *
     * @param fullRoomname
     * @return
     */
    public static String getRoomUserName(String fullRoomname) {
        return fullRoomname.split("/")[1];
    }

    /**
     * 获取用户信息
     *
     * @param
     * @return
     */
    // public VCard getUserInfo(String user) { // null 时查自己
    // try {
    // VCard vcard = new VCard();
    // // 加入这句代码，解决No VCard for
    // ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp",
    // new VCardProvider());
    // if (user == null) {
    // vcard.load(getConnection());
    // } else {
    // vcard.load(getConnection(), user + "@" + Constants.SERVER_NAME);
    // }
    // if (vcard != null)
    // return vcard;
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // return null;
    // }
    public void closeConnection() {
        if (con != null) {
            try {
                con.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        con = null;
        ProviderManager.getInstance().removeIQProvider("muc", "MZH");
    }

    public List<String> getMembers() {
        List<String> list = new ArrayList<>();
        Roster roster = getConnection().getRoster();
//                    SystemClock.sleep(10000);
        Collection<RosterEntry> coll = roster.getEntries();
        for (RosterEntry rosterEntry : coll) {
            String name = rosterEntry.getName();
            String user2 = rosterEntry.getUser();
            System.out.println("name>>>>>>>>>" + name);
            System.out.println("user>>>>>>>>>" + user2);
            list.add(user2);
        }
        return list;
    }

    public class MUCPacketExtensionProvider implements IQProvider {
        @Override
        public IQ parseIQ(XmlPullParser parser) throws Exception {
            int eventType = parser.getEventType();
            myRooms.clear();
            leaveRooms.clear();
            Room info = null;
            while (true) {
                if (eventType == XmlPullParser.START_TAG) {
                    if ("room".equals(parser.getName())) {
                        // admin1@192.168.2.67/Smack
                        String account = parser
                                .getAttributeValue("", "account");
                        // 123456
                        String roomName = parser.getAttributeValue("",
                                "roomName");
                        // 1
                        String roomJid = parser
                                .getAttributeValue("", "roomJid");
                        info = new Room();
                        info.name = roomName;
                        info.roomid = roomJid;
                        myRooms.add(info);
                    }

                    if ("friend".equals(parser.getName())) {
                        info.friendList.add(XmppTool.getInstance().getUsername(
                                parser.nextText()));
                    }
                } else if (eventType == XmlPullParser.END_TAG) {
                    if ("muc".equals(parser.getName())) {
                        break;
                    }
                }
                eventType = parser.next();
            }
            return null;
        }

    }

}
